import { login, login1, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    severUserInfo: {},
    token: getToken()
  },
  getters: {
    userInfo: state => state.severUserInfo
  },
  mutations: {
    setSeverUserInfo (state, severUserInfo) {
      state.severUserInfo = severUserInfo
      console.log('state', severUserInfo)
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    handleLogin ({ commit }, { userName, password, code }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          code
        }).then(res => {
          const data = res.data
          if (data.errcode === 0) {
            commit('setToken', data.data.key)
          }
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 免密登录方式
    handleLogin1 ({ commit }, { params }) {
      return new Promise((resolve, reject) => {
        login1(params).then(res => {
          const data = res.data
          if (data.errcode === 0) {
            commit('setToken', data.data.key)
          }
          resolve(data)
        }).catch(err => {
          console.log(111122)
          reject(err)
        })
      })
    },
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // logout().then(() => {
        //  commit('setToken', '')
        //  commit('setAccess', [])
        //  resolve()
        // }).catch(err => {
        //  reject(err)
        // })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        resolve()
      })
    },
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data.data
            console.log('!!!!!!!!@!!12344', data)
            commit('setSeverUserInfo', data)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
